package com.zbcz.crm.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.zbcz.crm.bean.FollowUpRecord
import com.zbcz.crm.databinding.ItemFollowUpRecordBinding
import com.zbcz.crm.network.RetrofitManager

import com.zbcz.crm.util.setRoundedCorners

/**
 *  跟进记录适配器
 */
class FollowUpRecordAdapter(private val dataList: List<FollowUpRecord>) :
    RecyclerView.Adapter<FollowUpRecordAdapter.FollowUpRecordHolder>() {

    private val expandedStates = mutableMapOf<Int, Boolean>()

    inner class FollowUpRecordHolder(private val binding: ItemFollowUpRecordBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {
            binding.tvFold.setOnClickListener {
                toggleItemExpansion(adapterPosition)
            }
            binding.ivFold.setOnClickListener {
                toggleItemExpansion(adapterPosition)
            }
        }


        fun bind(data: FollowUpRecord) {
            binding.run {
                tvFollowNameValue.text = data.followerName
                tvFollowTimeValue.text = data.followDate
                tvFollowContentValue.text = data.followContent
                Glide.with(binding.root.context)
                    .load(RetrofitManager.getImageUrl(data.followImg))
                    .into(binding.ivFollowImg)
            }
            binding.contentParent.setRoundedCorners(45f)
        }

        fun setExpanded(expanded: Boolean) {
            val visible = if (expanded) View.VISIBLE else View.GONE
            binding.clFollowContent.visibility = visible
            binding.clFollowImg.visibility = visible
            binding.bottomDiver.visibility = visible
        }
    }

    private fun toggleItemExpansion(position: Int) {
        expandedStates[position] = !(expandedStates[position] ?: true)
        notifyItemChanged(position)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FollowUpRecordHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = ItemFollowUpRecordBinding.inflate(inflater, parent, false)
        return FollowUpRecordHolder(binding)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: FollowUpRecordHolder, position: Int) {
        holder.bind(dataList[position])
        // 设置展开或折叠的状态
        holder.setExpanded(expandedStates[position] ?: true)
    }
}